﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Stamp_For_Africa_Version_2.Models;

namespace Stamp_For_Africa_Version_2.Repositories
{
  public class CatalogueRepository
  {
    private StampsDataContext db = new StampsDataContext();
    //
    // Query Methods

    public IQueryable<Catalogue> FindAllCatalogues()
    {
      return db.Catalogues;
    }

    public Catalogue GetCatalogue(Guid id)
    {
      return db.Catalogues.SingleOrDefault(d => d.Id == id);
    }

    //
    // Insert/Delete Methods

    public void Add(Catalogue catalogue)
    {
      db.Catalogues.InsertOnSubmit(catalogue);
      Save();
    }

    public void Delete(Catalogue catalogue)
    {
      db.Catalogues.DeleteOnSubmit(catalogue);
    }

    public void AddStampToCatalog(Guid catalogId, Guid stampId, int catalogNumber)
    {
      CatalogueEntry catalogueEntry = new CatalogueEntry();
      catalogueEntry.Id = Guid.NewGuid();
      catalogueEntry.CatalogueId = catalogId;
      catalogueEntry.StampId = stampId;
      catalogueEntry.CatalogueNumber = catalogNumber;
      db.CatalogueEntries.InsertOnSubmit(catalogueEntry);
      Save();
    }

		public void RemoveCatalogueEntry(Guid catalogueEntryId)
		{
			CatalogueEntry catalogueEntry = db.CatalogueEntries.Where(u => u.Id == catalogueEntryId).SingleOrDefault();
			if (catalogueEntry != null)
			{
				db.CatalogueEntries.DeleteOnSubmit(catalogueEntry);
				Save();
			}
		}

    public CatalogueEntry GetCatalogEntry(Guid catalogId, Guid stampId)
    {
      return db.CatalogueEntries.Where(u => u.CatalogueId == catalogId && u.StampId == stampId).SingleOrDefault();
    }

    public List<CatalogueEntry> GetCatalogueEntriesForStamp(Guid stampId)
    {
      return db.CatalogueEntries.Where(u => u.StampId == stampId).ToList();
    }

    //
    // Persistence

    public void Save()
    {
      db.SubmitChanges();
    }
  }
}